import "./App.css";
import { Navigate, Outlet } from "react-router-dom";
import Main from "@/components/layout/main";
import Header from "@/components/layout/header";
import Footer from "@/components/layout/footer";
import { useEffect } from "react";
import { useRouteMeta } from "@/hooks/useRouteMeta";
import { useSelector, useDispatch } from "react-redux";
import { setWs } from "@/store/modules/wsStore";
import WS from "./utils/ws";
import WSChat from "@/components/chatBox";

export default function App() {
  const { title, requiresAuth }: any = useRouteMeta();
  const { token } = useSelector((state: any) => state.user);
  const dispatch = useDispatch();
  const wsStore = useSelector((state: any) => state.ws);

  useEffect(() => {
    if (title) {
      document.title = title;
    }
  }, [title]);

  useEffect(() => {
    if (token) {
      if (wsStore.ws === null) {
        const ws = new WS();
        ws.startConnection(token);
        dispatch(setWs(ws));
      } else {
        wsStore.ws.startConnection(token);
      }
    }
  }, [token]);

  if (requiresAuth && !token) {
    return <Navigate to={"/"} />;
  }

  return (
    <>
      <div id="app" className="app">
        <Header></Header>
        <Main>
          {token && <WSChat />}
          <Outlet />
        </Main>
        <Footer></Footer>
      </div>
    </>
  );
}
